package com.detrum.detrumdx.activity;

import android.Manifest;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.detrum.DeviceUpdateReceiver;
import com.detrum.DeviceUpdateReceiverCall;
import com.detrum.DownloadReceiver;
import com.detrum.ShareSettingActivity;
import com.detrum.base.BaseActivity;
import com.detrum.base.BaseStatic;
import com.detrum.base.ServiceStatic;
import com.detrum.bean.VersionBean;
import com.detrum.costomview.InfoShow;
import com.detrum.costomview.InfoShowCall;
import com.detrum.costomview.WrapListView;
import com.detrum.detrumdata.service.USBConnetService;
import com.detrum.detrumdata.service.UsbServiceCall1;
import com.detrum.detrumdx.R;
import com.detrum.detrumdx.adapter.DeviceAdapter;
import com.detrum.service.DownloadReceiveCall;
import com.detrum.sportcamera.finals.SportStatic;
import com.detrum.sportcamera.service.WifiService;
import com.detrum.sportcamera.service.WifiServiceCallback2;
import com.detrum.sportcamera.service.WifiServiceCallback5;
import com.detrum.sqlite.SqliteMediaOperation;
import com.detrum.sqlite.SqliteVersionOperate;
import com.detrum.utils.HttpDataManager;
import com.detrum.utils.LogUtils;
import com.detrum.utils.MyMethod;
import com.detrum.utils.MyOkHttpHelper;
import com.detrum.utils.PermissionCall;
import com.detrum.utils.PermissionRegister;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.detrum.base.BaseStatic.NetPath;
import static com.detrum.base.BaseStatic.savaInfoToSD;

public class SelfInfoActivity extends BaseActivity implements View.OnClickListener, InfoShowCall, PermissionCall, DownloadReceiveCall,
        DeviceUpdateReceiverCall {
    private RelativeLayout cleanCache, deviceInfo, appInfo, share_rl;
    private LinearLayout cache_ll, app_ll;
    private ImageView cache_allow, device_allow, app_allow;
    private boolean cache_show, device_show, app_show, isResume;
    private InfoShow cache_info, data_info, app_1;
    private WrapListView device_list;
    private View list_divider;
    private DeviceAdapter deviceAdapter;
    private List<VersionBean> list;
    private PermissionRegister permissionRegister;
    private DownloadReceiver downloadReceiver;
    private DeviceUpdateReceiver deviceUpdateReceiver;

    private ProgressBar device_progress, app_progress;
    private TextView device_update_info;
    private boolean isExistCard = true;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 11) {
                if (msg.arg1 > 1000000) {
                    cache_info.setInfo(msg.arg1 / 1000000 + "M");
                } else if (msg.arg1 < 1000000 && msg.arg1 > 1000) {
                    cache_info.setInfo(msg.arg1 / 1000 + "Kb");
                } else if (msg.arg1 < 1000) {
                    cache_info.setInfo(msg.arg1 + "b");
                }
                cache_info.setBtnPadding(3);
            } else if (msg.what == 12) {
                if (msg.arg1 >= 1000000) {
                    data_info.setInfo(msg.arg1 / 1000000 + "M");
                } else if (msg.arg1 < 1000000 && msg.arg1 >= 1000) {
                    data_info.setInfo(msg.arg1 / 1000 + "Kb");
                } else if (msg.arg1 < 1000) {
                    data_info.setInfo(msg.arg1 + "b");
                }
                data_info.setBtnPadding(3);
            } else if (msg.what == 13) {
                if (list != null && list.size() != 0) {
                    int size = list.size();
                    LogUtils.i("Device size ==================== " + size);
                    List<VersionBean> beans = new ArrayList<>();
                    for (VersionBean bean : list) {
                        if (bean.getDeviceVersion() == null || bean.getDeviceVersion().length() == 0) {
                            beans.add(bean);
                        }
                    }
                    list.removeAll(beans);
                    size = list.size();
                    LogUtils.i("Device size =========2222=========== " + size);
                    deviceAdapter = new DeviceAdapter(SelfInfoActivity.this, list, size);
                    device_list.setAdapter(deviceAdapter);
                    device_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            device_list.setEnabled(false);
                            BaseStatic.deviceName = list.get(position).getName();
                            BaseStatic.deviceNetVersion = list.get(position).getNetVersion();
                            BaseStatic.deviceVersion = list.get(position).getDeviceVersion();
                            BaseStatic.deviceNetPath = list.get(position).getFilePath();
                            BaseStatic.deviceNetImagePath = list.get(position).getImagePath();
                            BaseStatic.deviceNetMessage = list.get(position).getUpdataMsg();
                            BaseStatic.deviceNetMsgPath = list.get(position).getUpdataFilePath();
                            BaseStatic.deviceNetVerify = list.get(position).getVerify();
                            BaseStatic.deviceNetLength = list.get(position).getLength();
                            BaseStatic.deviceNetExplain = list.get(position).getExplain();
                            LogUtils.i(BaseStatic.deviceNetVersion + "\n" + BaseStatic.deviceNetPath + "\n" + BaseStatic.deviceVersion);
                            LogUtils.i(BaseStatic.deviceNetVerify + "\n" + BaseStatic.deviceNetLength + "\n" + BaseStatic.deviceNetExplain);
                            long netCode, Code;
                            if (BaseStatic.deviceNetVersion == null) {
                                netCode = 0;
                            } else {
                                netCode = Long.parseLong(BaseStatic.deviceNetVersion.substring(6));
                            }
                            if (BaseStatic.deviceVersion == null) {
                                return;
                            } else {
                                Code = Long.parseLong(BaseStatic.deviceVersion.substring(6));
                            }
                            LogUtils.i("Code = " + Code + "   netCode = " + netCode);
                            if (Code < netCode||netCode==0) {
                                if (BaseStatic.deviceName.contains("IWT")) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                        permissionRegister.CheckPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, R.string.device_download_msg, 6, SelfInfoActivity.this);
                                    } else {
                                        getVersion(VerFlag.IWT);
                                    }
                                } else if (BaseStatic.deviceName.contains("DCAM")) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                        permissionRegister.CheckPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, R.string.device_download_msg, 7, SelfInfoActivity.this);
                                    } else {
                                        getVersion(VerFlag.DCAMH);
                                    }
                                }

                            } else if (Code >= netCode) {
                                if (isResume) {
                                    MyMethod.ShowDialog(SelfInfoActivity.this, R.string.maxVersion);
                                }
                            }
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    device_list.setEnabled(true);
                                }
                            }, 5000);
                        }
                    });
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_self_info);
        permissionRegister = new PermissionRegister(this);

        downloadReceiver = new DownloadReceiver();
        downloadReceiver.setDownloadReceiveCall(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction("downloadDevice");
        filter.addAction("download");
        filter.addAction("downloadFail");
        registerReceiver(downloadReceiver, filter);

        deviceUpdateReceiver = new DeviceUpdateReceiver();
        deviceUpdateReceiver.setDeviceUpdateReceiverCall(this);
        IntentFilter filter1 = new IntentFilter();
        filter1.addAction("deviceUpdate");
        registerReceiver(deviceUpdateReceiver, filter1);

        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                int count = 0;
                File dirfile = SelfInfoActivity.this.getApplicationContext().getCacheDir();
                if (dirfile.exists() && dirfile.isDirectory()) {
                    count = getLength(dirfile, count);
                }
                Message msg = new Message();
                msg.what = 11;
                msg.arg1 = count;
                handler.sendMessage(msg);

                int count2 = 0;
                File dirfile2 = new File(BaseStatic.MediaPath);
                if (dirfile.exists() && dirfile.isDirectory()) {
                    count2 = getLength(dirfile2, count2);
                }
                File dirfile3 = new File(BaseStatic.ThumbPath);
                if (dirfile.exists() && dirfile.isDirectory()) {
                    count2 = getLength(dirfile3, count2);
                }
                Message msg2 = new Message();
                msg2.what = 12;
                msg2.arg1 = count2;
                handler.sendMessage(msg2);

                list = SqliteVersionOperate.getInstance(SelfInfoActivity.this).SelectAll();
                handler.sendEmptyMessage(13);
            }
        }).start();
        app_1.setInfo(BaseStatic.appVersion);
        if (BaseStatic.appNetCode > BaseStatic.appCode) {
            app_1.updateShow(true);
        } else {
            app_1.updateShow(false);
        }
        app_1.setOnClickListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isResume = false;
        // TODO: 2018/5/4 wifi模块相关
        if (wifiService != null) {
            wifiService.LogoutDevice();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(downloadReceiver);
        unregisterReceiver(deviceUpdateReceiver);
        UnBindService();
    }

    private void initView() {
        cleanCache = findViewById(R.id.cleanCache);
        deviceInfo = findViewById(R.id.deviceInfo);
        appInfo = findViewById(R.id.appInfo);
        cache_ll = findViewById(R.id.cache_ll);
        app_ll = findViewById(R.id.app_ll);
        cache_allow = findViewById(R.id.cache_allow);
        device_allow = findViewById(R.id.device_allow);
        app_allow = findViewById(R.id.app_allow);
        cache_info = findViewById(R.id.cache_info);
        data_info = findViewById(R.id.data_info);
        app_1 = findViewById(R.id.app_1);
        device_list = findViewById(R.id.device_list);
        list_divider = findViewById(R.id.list_divider);

        device_progress = findViewById(R.id.device_progress);
        device_update_info = findViewById(R.id.device_update_info);
        app_progress = findViewById(R.id.app_progress);

        cleanCache.setOnClickListener(this);
        deviceInfo.setOnClickListener(this);
        appInfo.setOnClickListener(this);
        cache_info.setInfoShowCall(this);
        data_info.setInfoShowCall(this);
        app_1.setInfoShowCall(this);
    }


    @Override
    public void onClick(View v) {
        if (v == cleanCache) {
            if (cache_show) {
                hideAll();
            } else {
                showCache();
            }
        } else if (v == deviceInfo) {
            if (device_show) {
                hideAll();
            } else {
                if (list != null && list.size() != 0) {
                    showDevice();
                } else {
                    MyMethod.ShowDialog(SelfInfoActivity.this, R.string.connect_devcie);
                }
            }
        } else if (v == appInfo) {
            if (app_show) {
                hideAll();
            } else {
                showApp();
            }
        } else if (v == app_1) {
            app_1.setEnabled(false);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                permissionRegister.CheckPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, R.string.download_msg, 5, SelfInfoActivity.this);
            } else {
                getVersion(VerFlag.APP);
            }
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    app_1.setEnabled(true);
                }
            }, 5000);
        }
    }

    private void showApp() {
        hideAll();
        app_show = true;
        app_ll.setVisibility(View.VISIBLE);
        app_allow.setRotation(90);
    }

    private void showDevice() {
        hideAll();
        device_show = true;
        device_list.setVisibility(View.VISIBLE);
        list_divider.setVisibility(View.VISIBLE);
        device_allow.setRotation(90);
    }

    private void showCache() {
        hideAll();
        cache_show = true;
        cache_ll.setVisibility(View.VISIBLE);
        cache_allow.setRotation(90);
    }

    private void hideAll() {
        app_show = false;
        app_ll.setVisibility(View.GONE);
        app_allow.setRotation(0);

        device_show = false;
        device_list.setVisibility(View.GONE);
        list_divider.setVisibility(View.GONE);
        device_allow.setRotation(0);

        cache_show = false;
        cache_ll.setVisibility(View.GONE);
        cache_allow.setRotation(0);
    }

    @Override
    public void onInfoClick(View view) {
        if (view == cache_info) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    File dirfile = SelfInfoActivity.this.getApplicationContext().getCacheDir();
                    cleanCache(dirfile);
                    int count = 0;
                    count = getLength(dirfile, count);
                    Message msg = new Message();
                    msg.what = 11;
                    msg.arg1 = count;
                    handler.sendMessage(msg);
                }
            }).start();
        } else if (view == data_info) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //清除本地数据
                    File dirFile = new File(BaseStatic.MediaPath);
                    File dirFile2 = new File(BaseStatic.ThumbPath);
                    int count2 = 0;
                    if (dirFile.exists() && dirFile.isDirectory()) {
                        cleanCache(dirFile);
                        count2 = getLength(dirFile, count2);
                    }
                    if (dirFile2.exists() && dirFile2.isDirectory()) {
                        cleanCache(dirFile2);
                        count2 = getLength(dirFile2, count2);
                    }
                    //清除数据库数据
                    SqliteMediaOperation.getInstence(SelfInfoActivity.this).DeleteLocalAll();
                    Message msg2 = new Message();
                    msg2.what = 12;
                    msg2.arg1 = count2;
                    handler.sendMessage(msg2);
                }
            }).start();
        } else if (view == app_1) {

        }
    }

    private int getLength(File dirfile, int count) {
        File[] files1 = dirfile.listFiles();
        if (files1 == null || files1.length == 0) {
            return count;
        }
        for (int i = 0; i < files1.length; i++) {
            if (files1[i].isFile()) {
                count += files1[i].length();
            } else if (files1[i].isDirectory()) {
                count += getLength(files1[i], count);
            }
        }
        return count;
    }

    private void cleanCache(File dirfile) {
        File[] files1 = dirfile.listFiles();
        for (int i = 0; i < files1.length; i++) {
            LogUtils.e("delete file = " + files1[i].getPath());
            if (files1[i].isFile()) {
                files1[i].delete();
            } else if (files1[i].isDirectory()) {
                cleanCache(files1[i]);
            }
        }
    }

    @Override
    public void ScanWifi() {

    }

    @Override
    public void startUsbPreview() {

    }

    @Override
    public void startPreview() {

    }

    @Override
    public void getVersion(final PermissionCall.VerFlag flag) {
        if (flag == VerFlag.DCAMH) {
            if (MyMethod.isDevcieConnected(SelfInfoActivity.this)) {
                VersionBean bean = SqliteVersionOperate.getInstance(SelfInfoActivity.this).Select("DCAM-H");
                if (bean != null) {
                    String filePath = bean.getLocalFilePath();
                    if (filePath != null) {
                        File file = new File(filePath);
                        if (file.exists()) {
                            BindService(VerFlag.DCAMH);
                            return;
                        }
                    }
                }
                MyMethod.ShowDialog(SelfInfoActivity.this, R.string.connect_internet_download);
                return;
            } else {
                if (!MyMethod.isNetworkConnected(SelfInfoActivity.this)) {
                    MyMethod.ShowDialog(SelfInfoActivity.this, R.string.connect_internet_download);
                    return;
                }
            }
        }
        if (flag == VerFlag.IWT) {
            if (!MyMethod.isNetworkConnected(SelfInfoActivity.this) || MyMethod.isDevcieConnected(SelfInfoActivity.this)) {
                MyMethod.ShowDialog(SelfInfoActivity.this, R.string.connect_internet_download);
                return;
            }
        }
        if (flag == VerFlag.APP) {
            if (!MyMethod.isNetworkConnected(SelfInfoActivity.this) || MyMethod.isDevcieConnected(SelfInfoActivity.this)) {
                MyMethod.ShowDialog(SelfInfoActivity.this, R.string.connect_internet_download);
                return;
            }
        }
        MyOkHttpHelper.getInstance(SelfInfoActivity.this).doGet(NetPath, null).excute(1, new MyOkHttpHelper.OKCallBack() {
            @Override
            public void onFailure(int message) {
                if (isResume) {
                    MyMethod.ShowDialog(SelfInfoActivity.this, com.detrum.base.R.string.net_fault);
                }
            }

            @Override
            public void onInternetFail() {
                if (isResume) {
                    MyMethod.ShowDialog(SelfInfoActivity.this, com.detrum.base.R.string.net_show);
                }

            }

            @Override
            public void onResponse(String message) {
                LogUtils.i("message = " + message);
                if (message != null) {
                    HttpDataManager.getInstance().getVersion(SelfInfoActivity.this, message, new HttpDataManager.HttpManagerCall() {
                        @Override
                        public void success() {
                            LogUtils.i(BaseStatic.appNetCode + "---------------" + BaseStatic.appCode);
                            if (isResume) {
                                if (flag == VerFlag.APP) {
                                    if (BaseStatic.appNetCode > BaseStatic.appCode) {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                MyMethod.ShowDiaLogDownload(SelfInfoActivity.this, BaseStatic.appNetMessage);
                                            }
                                        });
                                    } else {
                                        String[] strs = BaseStatic.appNetPath.split("/");
                                        String name = strs[strs.length - 1];
                                        File file = new File(BaseStatic.path, name);
                                        if (file != null) {
                                            file.delete();
                                        }
                                        if (isResume) {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    MyMethod.ShowDialog(SelfInfoActivity.this, R.string.maxVersion);
                                                }
                                            });
                                        }
                                    }
                                } else {
                                    VersionBean bean = null;
                                    if (flag == VerFlag.DCAMH) {
                                        bean = SqliteVersionOperate.getInstance(SelfInfoActivity.this).Select("DCAM-H");
                                    } else if (flag == VerFlag.IWT) {
                                        bean = SqliteVersionOperate.getInstance(SelfInfoActivity.this).Select("IWT-AGS58");
                                    }
                                    BaseStatic.deviceNetVerify = bean.getVerify();
                                    BaseStatic.deviceVersion = bean.getDeviceVersion();
                                    BaseStatic.deviceNetLength = bean.getLength();
                                    BaseStatic.deviceNetPath = bean.getFilePath();
                                    BaseStatic.deviceNetVersion = bean.getNetVersion();
                                    BaseStatic.deviceNetMessage = bean.getUpdataMsg();
                                    long netCode, Code;
                                    if (BaseStatic.deviceNetVersion == null) {
                                        netCode = 0;
                                    } else {
                                        String[] netvers = BaseStatic.deviceNetVersion.split("\\.");
                                        netCode = Long.parseLong(netvers[netvers.length - 1]);
                                    }
                                    if (BaseStatic.deviceVersion == null) {
                                        Code = 0;
                                    } else {
                                        String[] vers = BaseStatic.deviceVersion.split("\\.");
                                        Code = Long.parseLong(vers[vers.length - 1]);
                                    }
                                    LogUtils.e("code = "+Code+"   netCode = "+netCode);
                                    if (Code < netCode) {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if (isResume) {
                                                    MyMethod.ShowDialogDownloadDevice(SelfInfoActivity.this, BaseStatic.deviceNetMessage);
                                                }
                                            }
                                        });
                                    } else {
                                        if (isResume) {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    MyMethod.ShowDialog(SelfInfoActivity.this, R.string.maxVersion);
                                                }
                                            });
                                        }
                                    }
                                }
                            }
                        }

                        @Override
                        public void fail(final int msg) {
                            if (isResume) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        MyMethod.ShowDialog(SelfInfoActivity.this, msg);
                                    }
                                });
                            }
                        }
                    });
                }
            }
        });
    }

    @Override
    public void Cancel() {

    }

    @Override
    public void downloadDeviceFinish(String path) {
        BaseStatic.deviceLocalPath = path;
        LogUtils.e("localPath = " + path);
        BaseStatic.savaInfoToSD("localPath = " + path);
        if (path.endsWith("DtSysFW.bin")) {
            new AlertDialog.Builder(this, R.style.loading_dialog)
                    .setMessage(R.string.device_update_iwt)
                    .setNegativeButton(R.string.updata, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            BindService(VerFlag.IWT);
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .create()
                    .show();
        } else if (path.endsWith("FpvCamSysFW.bin")) {
            new AlertDialog.Builder(this, R.style.loading_dialog)
                    .setMessage(R.string.device_download_finish_DCAM)
                    .setNegativeButton(R.string.confirm, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .create()
                    .show();
        }
    }

    @Override
    public void downloadDeviceProgress(int progress, int length) {
        device_progress.setVisibility(View.VISIBLE);
        device_progress.setMax(length);
        device_progress.setProgress(progress);
        if (progress == length) {
            device_progress.setVisibility(View.GONE);
        }
    }

    @Override
    public void downloadAppProgress(int progress, int length) {
        app_progress.setVisibility(View.VISIBLE);
        app_progress.setMax(length);
        app_progress.setProgress(progress);
        if (progress == length) {
            app_progress.setVisibility(View.GONE);
        }
    }

    @Override
    public void downloadFail() {
        if (isResume) {
            MyMethod.ShowDialog(SelfInfoActivity.this, R.string.device_file_exception);
        }
    }

    private Intent Usbintent, WifiIntent;

    private void BindService(VerFlag flag) {
        if (flag == VerFlag.IWT && ServiceStatic.isLaunchUsbService) {
            if (usbService != null) {
                usbService.updataDevice();
                BaseStatic.savaInfoToSD("开始更新Usb设备");
                return;
            }
            Usbintent = new Intent(SelfInfoActivity.this, USBConnetService.class);
            usbConn = new UsbConn();
            bindService(Usbintent, usbConn, BIND_AUTO_CREATE);
        } else if (flag == VerFlag.DCAMH && ServiceStatic.isWifiDeviceConnect) {
            // TODO: 2018/5/4 wifi模块相关
            if (wifiService != null && wifiConn != null) {
                if (SportStatic.isLoginPre) {
                    if (isExistCard) {
                        wifiService.WriteUpdateFile();
                    } else {
                        MyMethod.ShowDialog(SelfInfoActivity.this, R.string.device_save_null);
                    }
                } else {
                    handler.post(new LoginRun());
                }
                return;
            }
            WifiIntent = new Intent(SelfInfoActivity.this, WifiService.class);
            wifiConn = new WifiConn();
            if (!ServiceStatic.isWifiServiceStart) {
                startService(WifiIntent);
            }
            bindService(WifiIntent, wifiConn, BIND_AUTO_CREATE);
        }
    }

    private void UnBindService() {
        if (ServiceStatic.isLaunchUsbService) {
            if (usbConn != null) {
                unbindService(usbConn);
                usbConn = null;
            }
            // TODO: 2018/5/4 wifi模块相关
        } else if (ServiceStatic.isWifiServiceStart) {
            if (wifiConn != null) {
                unbindService(wifiConn);
                wifiConn = null;
            }
        }
    }

    private USBConnetService usbService;
    private UsbConn usbConn;

    @Override
    public void deviceUpdate(int position) {
        if (position == 1) {
            device_update_info.setText(R.string.device_loading);
        } else if (position == 2) {
            device_update_info.setText(R.string.device_install);
        } else if (position == 3) {
            device_update_info.setText(R.string.device_restart);
        } else if (position == 4) {
            device_update_info.setText(R.string.device_activate);
        } else {
            device_update_info.setText("");
        }
    }

    private class UsbConn implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            usbService = ((USBConnetService.UsbBinder) service).getService();
            usbService.setUsbServiceCall1(new UsbServiceCall1() {
                @Override
                public void connect() {

                }

                @Override
                public void disconnect() {
                    savaInfoToSD("SelfInfoActivity usbService disconnect launch = " + ServiceStatic.isLaunchUsbService);
                    if (!isResume) {
                        return;
                    }
                    if (ServiceStatic.isLaunchUsbService) {
                        if (usbConn != null) {
                            unbindService(usbConn);
                            usbConn = null;
                        }
                        stopService(Usbintent);
                    }
                }

                @Override
                public void onVersion(boolean isSuccess) {

                }
            });
            usbService.updataDevice();
            BaseStatic.savaInfoToSD("bind开始更新设备");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    // TODO: 2018/5/4 wifi模块相关
    private WifiService wifiService;
    private WifiConn wifiConn;
    private int loginNum;

    private class WifiConn implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            wifiService = ((WifiService.WifiBinder) service).getService();
            LogUtils.i("SelfInfoActivity wifiService 绑定成功");
            wifiService.setWifiServiceCallback2(new WifiServiceCallback2() {
                @Override
                public void LoginSuccess() {
                    loginNum = 0;
                    if (isExistCard) {
                        wifiService.WriteUpdateFile();
                    } else {
                        MyMethod.ShowDialog(SelfInfoActivity.this, R.string.device_save_null);
                    }
                }

                @Override
                public void LoginFail() {
                    if (isResume) {
                        MyMethod.ShowDialog(SelfInfoActivity.this, R.string.device_login_fail);
                    }
                }

                @Override
                public void Disconnect() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (ServiceStatic.isWifiServiceStart) {
                                if (wifiConn != null) {
                                    try {
                                        unbindService(wifiConn);
                                        wifiConn = null;
                                    } catch (Exception e) {

                                    }
                                }
                            }
                            if (!ServiceStatic.isWifiDeviceConnect && isResume) {
                                MyMethod.ShowDialog(SelfInfoActivity.this, R.string.device_disconnect);
                            }
                        }
                    });
                }

                @Override
                public void NoCard() {
                    isExistCard = false;
                }
            });
            wifiService.setWifiServiceCallback5(new WifiServiceCallback5() {
                @Override
                public void indexFail() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (isResume) {
                                MyMethod.ShowDialog(SelfInfoActivity.this, R.string.device_update_fail);
                            }
                        }
                    });

                }

                @Override
                public void fileEmpty() {
                    LogUtils.i("SelfInfoActivity fileEmpty isResume = " + isResume);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (isResume) {
                                MyMethod.ShowDialog(SelfInfoActivity.this, R.string.device_update_file_null);
                            }
                        }
                    });

                }

                @Override
                public void updateDevice(final int position) {
                    LogUtils.i("SelfInfoActivity position = " + position);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (position == 1) {
                                device_update_info.setText(R.string.device_loading);
                            } else if (position == 2) {
                                device_update_info.setText(R.string.device_install);
                            } else if (position == 3) {
                                device_update_info.setText(R.string.device_restart);
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        device_update_info.setText("");
                                    }
                                }, 1000);
                            } else {
                                device_update_info.setText("");
                            }
                        }
                    });

                }

                @Override
                public void installFail() {
                    if (isResume) {
                        MyMethod.ShowDialog(SelfInfoActivity.this, R.string.device_install_fail);
                    }
                    device_update_info.setText("");
                }

                @Override
                public void Disconnect() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (ServiceStatic.isWifiServiceStart && isResume) {
                                if (wifiConn != null) {
                                    unbindService(wifiConn);
                                    wifiConn = null;
                                }
                                if (isResume) {
                                    MyMethod.ShowDialog(SelfInfoActivity.this, R.string.device_disconnect);
                                }
                            }
                        }
                    });

                }
            });
            if (SportStatic.isLoginPre) {
                if (isExistCard) {
                    wifiService.WriteUpdateFile();
                } else {
                    MyMethod.ShowDialog(SelfInfoActivity.this, R.string.device_save_null);
                }
            } else {
                handler.postDelayed(new LoginRun(), 2000);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            if (wifiService != null) {
                wifiService = null;
            }
        }
    }

    private class LoginRun implements Runnable {

        @Override
        public void run() {
            if (wifiService != null && wifiConn != null) {
                if (loginNum < 2) {
                    if (!SportStatic.isLoginPre) {
                        loginNum++;
                        wifiService.LoginDevice();
                        handler.postDelayed(this, 2000);
                    }
                } else {
                    if (isResume) {
                        MyMethod.ShowDialog(SelfInfoActivity.this, R.string.device_update_timeout);
                    }
                }
            } else {
                BindService(VerFlag.DCAMH);
            }
        }
    }
}
